package com.playtruly.wanzhende2025

import androidx.multidex.MultiDexApplication
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import cn.jpush.android.api.JPushInterface

/**
 * 玩真的2 自定义Application类
 * 集成多dex支持和各种SDK初始化
 */
class PlayTrulyApplication : MultiDexApplication() {

    override fun onCreate() {
        super.onCreate()
        
        // 🔔 初始化极光推送
        initJPush()
        
        // 🔥 预热Flutter引擎以提升启动速度
        initFlutterEngine()
    }

    /**
     * 🔔 初始化极光推送 - 按官方文档配置
     */
    private fun initJPush() {
        try {
            // 设置调试模式，发布时改为false
            JPushInterface.setDebugMode(true)
            
            // 初始化JPush
            JPushInterface.init(this)
            
            android.util.Log.d("PlayTrulyApp", "🚀 极光推送初始化完成")
            android.util.Log.d("PlayTrulyApp", "📱 AppKey: 09a7d1e089ee25fde90cde49")
            
            // 延迟检查状态（让JPush有时间完成初始化）
            android.os.Handler(mainLooper).postDelayed({
                JPushUtil.checkJPushStatus(this)
            }, 5000) // 增加到5秒，给JPush更多初始化时间
            
        } catch (e: Exception) {
            android.util.Log.e("PlayTrulyApp", "❌ 极光推送初始化失败", e)
        }
    }

    /**
     * 🔥 预热Flutter引擎
     */
    private fun initFlutterEngine() {
        try {
            // 创建Flutter引擎并缓存
            val flutterEngine = FlutterEngine(this)
            
            // 开始执行Dart代码
            flutterEngine.dartExecutor.executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
            )

            // 缓存Flutter引擎
            FlutterEngineCache
                .getInstance()
                .put("play_truly_engine", flutterEngine)
                
            android.util.Log.d("PlayTrulyApp", "Flutter引擎预热完成")
        } catch (e: Exception) {
            android.util.Log.e("PlayTrulyApp", "Flutter引擎预热失败", e)
        }
    }
}